package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Comment;
import com.ruoyi.system.domain.Post;
import com.ruoyi.system.domain.dto.PostDTO;
import com.ruoyi.system.es.CommentDocument;
import com.ruoyi.system.es.CommentRepository;
import com.ruoyi.system.es.PostDocument;
import com.ruoyi.system.es.PostRepository;
import com.ruoyi.system.mapper.CommentMapper;
import com.ruoyi.system.mapper.MembersMapper;
import com.ruoyi.system.mapper.PostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.IPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 帖子管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-25
 */
@Service
public class PostServiceImpl implements IPostService {
    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private MembersMapper membersMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private PostRepository postRepository;
    @Autowired
    private CommentRepository commentRepository;

    /**
     * 查询帖子
     *
     * @param id 帖子主键
     * @return 帖子
     */
    @Override
    public Post selectPostById(Long id) {
        return postMapper.selectPostById(id);
    }

    /**
     * 查询帖子列表
     *
     * @param post 帖子
     * @return 帖子
     */
    @Override
    public List<Post> selectPostList(Post post) {
        Long userId = SecurityUtils.getUserId();
        List<SysRole> sysRoles = sysRoleMapper.selectRolesByUserId(userId);
        List<String> roleName = sysRoles.stream().map(SysRole::getRoleName).collect(Collectors.toList());
        PageUtils.startPage();
        if (roleName.contains("超级管理员")) {
            return postMapper.selectPostList(post);
        }
        return postMapper.selectPostListByUserId(post, userId);
    }

    /**
     * 新增帖子
     *
     * @return 结果
     */
    @Override
    public int insertPost(PostDTO postDTO) {
        Post post = BeanUtil.toBean(postDTO, Post.class);
        post.setIsTop(postDTO.getIsTop() ? 1 : 0);
        // 设置作者ID为当前用户
        post.setAuthorId(SecurityUtils.getUserId());
        post.setCreatedAt(new Date());
        post.setUpdatedAt(new Date());
        // 设置默认值
        if (post.getViewCount() == null) post.setViewCount(0);
        if (post.getLikeCount() == null) post.setLikeCount(0);
        if (post.getCommentCount() == null) post.setCommentCount(0);
        if (post.getStatus() == null) post.setStatus(1); // 默认已发布
        if (post.getIsTop() == null) post.setIsTop(0); // 默认不置顶
        int result = postMapper.insertPost(post);
        if (result > 0) {
            PostDocument doc = new PostDocument();
            doc.setSId(post.getId().toString());
            doc.setId(post.getId()+":post");
            doc.setTitle(post.getTitle());
            doc.setContent(post.getContent());
            doc.setAuthor(SecurityUtils.getUsername());
            doc.setCreateTime(post.getCreatedAt());
            postRepository.save(doc);
        }
        return result;
    }

    /**
     * 修改帖子
     *
     * @param post 帖子
     * @return 结果
     */
    @Override
    public int updatePost(Post post) {
        post.setUpdatedAt(new Date());
        int result = postMapper.updatePost(post);
/*        if (result > 0) {
            PostDocument doc = new PostDocument();
            doc.setId(post.getId()+":post");
            doc.setTitle(post.getTitle());
            doc.setContent(post.getContent());
            doc.setAuthor(post.getAuthorName());
            doc.setCreateTime(post.getCreatedAt());
            postRepository.save(doc);
        }*/
        return result;
    }

    /**
     * 批量删除帖子
     *
     * @param ids 需要删除的帖子主键
     * @return 结果
     */
    @Override
    public int deletePostByIds(Long[] ids) {
        return postMapper.deletePostByIds(ids);
    }

    /**
     * 删除帖子信息
     *
     * @param id 帖子主键
     * @return 结果
     */
    @Override
    public int deletePostById(Long id) {
        int result = postMapper.deletePostById(id);
        if (result > 0) {
            postRepository.deleteById(id+":post");
        }
        return result;
    }

    /**
     * 获取用户可发帖的社团列表
     *
     * @return 社团列表
     */
    @Override
    public List<Post> getUserClubs() {
        // 这里应该返回用户已加入的社团列表
        // 暂时返回所有社团，实际应该根据用户权限过滤
        Long userId = SecurityUtils.getUserId();

        return postMapper.selectUserClubs(userId);
    }

    /**
     * 查询评论列表
     *
     * @param comment 评论
     * @return 评论集合
     */
    @Override
    public List<Comment> selectCommentList(Comment comment) {
        return commentMapper.selectCommentList(comment);
    }

    /**
     * 新增评论
     *
     * @param comment 评论
     * @return 结果
     */
    @Override
    public int insertComment(Comment comment) {
        // 设置评论者ID为当前用户
        comment.setAuthorId(SecurityUtils.getUserId());
        comment.setCreatedAt(new Date());
        comment.setUpdatedAt(new Date());
        if (comment.getLikeCount() == null) comment.setLikeCount(0);

        // 插入评论
        int result = commentMapper.insertComment(comment);
        if (result>0){
            CommentDocument doc = new CommentDocument();
            doc.setId(comment.getId()+":comment");
            doc.setPostId(comment.getPostId());
            doc.setContent(comment.getContent());
            doc.setAuthor(SecurityUtils.getUsername());
            doc.setCreateTime(comment.getCreateTime());
            commentRepository.save(doc);
        }

        // 更新帖子的评论数
        if (result > 0) {
            postMapper.increaseCommentCount(comment.getPostId());
        }

        return result;
    }

    /**
     * 点赞评论
     *
     * @param commentId 评论ID
     * @return 结果
     */
    @Override
    public int likeComment(Long commentId) {
        return commentMapper.increaseLikeCount(commentId);
    }

    /**
     * 点赞帖子
     *
     * @param postId 帖子ID
     * @return 结果
     */
    @Override
    public int likePost(Long postId) {
        return postMapper.increaseLikeCount(postId);
    }

    /**
     * 增加浏览量
     *
     * @param postId 帖子ID
     * @return 结果
     */
    @Override
    public int increaseViewCount(Long postId) {
        return postMapper.increaseViewCount(postId);
    }
} 